package com.cx.common.core.utils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cx.common.core.dto.QueryCondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 条件查询工具
 *
 * @date 2023.03.11
 */
@Slf4j
public class QueryConditionToQueryWrapperConverter {

    enum OperatorType {
        /**
         * 等于
         */
        EQ,
        /**
         * 不等
         */
        NE,
        /**
         * 小于
         */
        LT,
        /**
         * 小于等于
         */
        LE,
        /**
         * 大于
         */
        GT,
        /**
         * 大于等于
         */
        GE,
        /**
         * 模糊匹配
         */
        LIKE,
        /**
         * 范围
         */
        BETWEEN,
        /**
         * 范围
         */
        IN;
    }

    enum OrderByType {
        /**
         * 升序
         */
        ASC,
        /**
         * 降序
         */
        DESC;
    }

    enum JavaType {
        /**
         * 数据类型 Integer
         */
        INTEGER("Integer"),
        /**
         * 数据类型 Long
         */
        LONG("Long"),
        /**
         * 数据类型 String
         */
        STRING("String"),
        /**
         * 数据类型 Double
         */
        DOUBLE("Double"),
        /**
         * 数据类型 BigDecimal
         */
        BIG_DECIMAL("BigDecimal"),
        /**
         * 数据类型 Boolean
         */
        BOOLEAN("Boolean"),
        /**
         * 数据类型 Date
         */
        DATE("Date");

        public final String code;

        JavaType(String code) {
            this.code = code;
        }
    }

    /**
     * 条件查询构造器
     *
     * @param queryCondition
     * @param dataObjectClass
     * @param <D>
     * @return
     */
    public static <D> QueryWrapper<D> convert(QueryCondition queryCondition, Class<D> dataObjectClass) {
        QueryWrapper<D> queryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(queryCondition.getPredicates())) {
            queryCondition.getPredicates().forEach(predicate -> {
                List valueList = convertStringToJavaType(predicate.getValues(), predicate.getProperty(), dataObjectClass);
                String property = getColumnName(predicate.getProperty(), dataObjectClass);

                OperatorType operateType = OperatorType.valueOf(predicate.getOperator().toUpperCase());
                switch (operateType) {
                    case EQ:
                        queryWrapper.eq(property, valueList.get(0));
                        break;
                    case NE:
                        queryWrapper.ne(property, valueList.get(0));
                        break;
                    case LE:
                        queryWrapper.le(property, valueList.get(0));
                        break;
                    case LT:
                        queryWrapper.lt(property, valueList.get(0));
                        break;
                    case GE:
                        queryWrapper.ge(property, valueList.get(0));
                        break;
                    case GT:
                        queryWrapper.gt(property, valueList.get(0));
                        break;
                    case LIKE:
                        queryWrapper.like(property, valueList.get(0));
                        break;
                    case IN:
                        queryWrapper.in(property, valueList);
                        break;
                    case BETWEEN:
                        queryWrapper.between(property, valueList.get(0), valueList.get(1));
                        break;
                    default:
                        throw new RuntimeException("no such operator type");
                }
            });
        }

        if (!CollectionUtils.isEmpty(queryCondition.getOrderBy())) {
            queryCondition.getOrderBy().forEach(orderBy -> {
                String property = getColumnName(orderBy.getProperty(), dataObjectClass);

                OrderByType type = OrderByType.valueOf(orderBy.getType().toUpperCase());
                switch (type) {
                    case ASC:
                        queryWrapper.orderByAsc(property);
                        break;
                    case DESC:
                        queryWrapper.orderByDesc(property);
                        break;
                    default:
                        throw new RuntimeException("no such orderBy type");
                }
            });
        }

        return queryWrapper;
    }

    /**
     * 属性转换
     *
     * @param values
     * @param property
     * @param dataObjectClass
     * @return
     */
    private static List convertStringToJavaType(List<String> values, String property, Class dataObjectClass) {
        Field field = null;
        try {
            field = dataObjectClass.getDeclaredField(property);
        } catch (NoSuchFieldException e) {
            log.error("数据模型中不存在该属性: " + property);
            throw new RuntimeException(e);
        }
        List valueList = new ArrayList<>();
        String javaType = field.getType().getSimpleName();
        if (JavaType.INTEGER.code.equals(javaType)) {
            for (String value : values) {
                valueList.add(Integer.parseInt(value));
            }
        } else if (JavaType.LONG.code.equals(javaType)) {
            for (String value : values) {
                valueList.add(Long.parseLong(value));
            }
        } else if (JavaType.BIG_DECIMAL.code.equals(javaType)) {
            for (String value : values) {
                valueList.add(new BigDecimal(value));
            }
        } else if (JavaType.DOUBLE.code.equals(javaType)) {
            for (String value : values) {
                valueList.add(Double.parseDouble(value));
            }
        } else if (JavaType.BOOLEAN.code.equals(javaType)) {
            for (String value : values) {
                valueList.add(Boolean.parseBoolean(value));
            }
        } else if (JavaType.DATE.code.equals(javaType)) {
            for (String value : values) {
                try {
                    valueList.add(new SimpleDateFormat().parse(value));
                } catch (ParseException e) {
                    log.error("日期格式可能存在问题: " + value);
                    throw new RuntimeException("日期格式可能存在问题: " + value);
                }
            }
        } else if (JavaType.STRING.code.equals(javaType)) {
            return values;
        } else {
            throw new RuntimeException("No such javaType");
        }
        return valueList;
    }

    /**
     * 通过属性名获取列名
     *
     * @param property
     * @param doClass
     * @return
     */
    private static String getColumnName(String property, Class doClass) {
        Field field = null;
        try {
            field = doClass.getDeclaredField(property);
        } catch (NoSuchFieldException e) {
            log.error("数据模型中不存在该属性: " + property);
            throw new RuntimeException("数据模型中不存在该属性: " + property);
        }

        TableField annotation = field.getAnnotation(TableField.class);
        if (null != annotation && null != annotation.value()){
            return annotation.value();
        }

        return camelToUnderline(property);

    }

    /**
     * 驼峰转下划线
     *
     * @param property
     * @return
     */
    public static String camelToUnderline(String property) {
        if (null == property || "".equals(property)) {
            return "";
        }
        if (property.length() == 1) {
            return property.toLowerCase();
        }

        char[] chars = property.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (i == 0) {
                sb.append(String.valueOf(c).toLowerCase());
            } else {
                if (isAsciiAlphaUpper(c)) {
                    sb.append("_" + String.valueOf(c).toLowerCase());
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 是否大写字母
     *
     * @param ch
     * @return
     */
    public static boolean isAsciiAlphaUpper(char ch) {
        return ch >= 'A' && ch <= 'Z';
    }
}